package com.member.common.utils;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.List;

public class WeChatUtil {

    /**
     * 获取token
     */
    private static String ACCESSTOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";

    /**
     * 获取所有公众号的粉丝
     */
    private static String OPENIDLIST = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={token}&next_openid=";

    /**
     * 从页面微信授权 过来获取的Unionid
     */
    private static String WEBSITINFO = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type=authorization_code";

    /**
     * 发送客服消息
     */
    private static String SENDMSG = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";

    public static void main(String[] args) {
        String accessToken = getAccessToken("wx741e48b2a94b19ca", "24a4aa9c67514ac5316f13a6736c5908");
        List<String> openidList = getOpenidList(accessToken);
        for (String s : openidList) {
            String unionid = getUnionid(accessToken, s);
            System.out.println(openidList);
            System.out.println(unionid);
        }

    }

    /**
     * 获取登陆的token
     *
     * @param appId
     * @param appSecret
     * @return
     * @throws Exception
     */
    public static String getAccessToken(String appId, String appSecret) {
        String url = ACCESSTOKENURL.replace("{appId}", appId).replace("{appSecret}", appSecret);
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        if (StringUtils.isNotBlank(result)) {
            return JSONObject.parseObject(result).getString("access_token");
        }
        return null;
    }

    /**
     * 获取公众号所有粉丝openID
     *
     * @param token
     * @return
     */
    public static List<String> getOpenidList(String token) {
        String url = OPENIDLIST.replace("{token}", token);
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("data");
            List<String> openids = (List<String>) jsonObject.get("openid");
            return openids;
        }
        return null;
    }

    /**
     * 根据openid 获取Unionid
     *
     * @param token
     * @param openid
     * @return
     */
    public static String getUnionid(String token, String openid) {
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + openid + "&lang=zh_CN";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        if (StringUtils.isNotBlank(result)) {
            return JSONObject.parseObject(result).getString("unionid");
        }
        return null;
    }

    /**
     * 从页面微信授权 过来获取的Unionid
     *
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public static String getPageUnionid(String appId, String appSecret, String code) {
        String url = WEBSITINFO.replace("{appId}", appId).replace("{appSecret}", appSecret).replace("{code}", code);
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        if (StringUtils.isNotBlank(result)) {
            return JSONObject.parseObject(result).getString("unionid");
        }
        return null;
    }


    public static String sendMsg(String content, String touser, String token) {
        String url = SENDMSG + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        String sb = "{" + "'touser'" + ":" + "'" + touser + "'" + "," + "'msgtype'" + ":" + "'text'" + "," + "'text'" + ":" +
                "{" + "'content'" + ":" + "'" + content + "'" + "}" + "}";
        JSONObject jsonObj = JSONObject.parseObject(sb);
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
        String result = restTemplate.postForObject(url, formEntity, String.class);
        if (StringUtils.isNotBlank(result)) {
            return result;
        }
        return null;
    }

}
